mod mem_manager; // 引入我们刚刚创建的模块

use mem_manager::{
    load_mem_img, pub_coords_to_offset, save_mem_img, PUB_SEGMENT_HEIGHT,
    PUB_SEGMENT_WIDTH, TOTAL_MEMORY_SIZE, SYS_SEGMENT_SIZE
};
use std::{
    env,
    path::PathBuf,
    // fs, // 不再需要fs来处理iteration文件
    // io::{self, Read, Write}, // 不再需要io::Read/Write来处理iteration文件
    // time::Duration, // 不再需要thread::sleep
    // thread // 如果不再需要Duration和sleep，thread模块也就不需要了
};

/// 执行 SET_COLOR 指令：
/// 直接修改内存中指定 (x, y) 坐标的像素颜色
fn execute_set_color(memory: &mut [u8], x: usize, y: usize, color_value: u8) {
    if let Some(offset) = pub_coords_to_offset(x, y) {
        if offset < memory.len() {
            memory[offset] = color_value;
            // println!("DEBUG: SET_COLOR at ({}, {}) to {} (offset {})", x, y, color_value, offset);
        } else {
            eprintln!("ERROR: Calculated offset {} is out of bounds for memory array of size {} while setting color at ({}, {})", offset, memory.len(), x, y);
        }
    } else {
        eprintln!("WARN: Coordinates ({}, {}) are out of bounds for Public Segment ({}x{})", x, y, PUB_SEGMENT_WIDTH, PUB_SEGMENT_HEIGHT);
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = env::args().collect();
    let mem_img_path = args
        .get(1)
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("mem.img"));

    println!("\n--- 观天道 (Data Bank: The Tao Computer) - Core Verification (Single Cycle, No Iteration Tracking) ---");
    println!("MEM_IMG Path: {:?}", mem_img_path);
    println!("Public Segment: {}x{} pixels ({} bytes)", PUB_SEGMENT_WIDTH, PUB_SEGMENT_HEIGHT, mem_manager::PUB_SEGMENT_SIZE);
    println!("Total Memory Size: {} bytes ({} KB)", TOTAL_MEMORY_SIZE, TOTAL_MEMORY_SIZE / 1024);
    println!("System Segment Size: {} bytes ({} KB)", SYS_SEGMENT_SIZE, SYS_SEGMENT_SIZE / 1024);
    println!("--- IMPORTANT: Please run 'python init_mem.py' first to initialize mem.img ---");

    // 每次运行都是一个独立的周期，不再依赖上一次的迭代计数
    println!("\n--- TAO Cycle ---");

    // 1. 加载当前世界状态
    let mut memory = match load_mem_img(&mem_img_path) {
        Ok(mem) => {
            println!("INFO: Successfully loaded mem.img.");
            mem
        },
        Err(e) => {
            eprintln!(
                "ERROR: Failed to load mem.img: {}. \
                Ensure 'mem.img' exists and is correctly initialized by 'init_mem.py'.", e
            );
            return Err(e.into());
        }
    };

    // 2. 模拟硬编码的 SET_COLOR 指令执行
    // 暂时保持一个简单的、不变的指令，用于验证SET_COLOR功能
    println!("INFO: Executing hardcoded SET_COLOR instruction (fixed pixel)...");

    // 每次运行都将 (0,0) 设置为 255 (白色)
    // 未来这里将替换为从 commands.queue 读取并解析的指令
    execute_set_color(&mut memory, 0, 0, 255);
    println!("  -> Pixel (0, 0) set to color 255");


    // 3. 原子性保存更新后的世界状态
    match save_mem_img(&mem_img_path, &memory) {
        Ok(_) => println!("INFO: Successfully saved mem.img."),
        Err(e) => {
            eprintln!("ERROR: Failed to save mem.img: {}", e);
            return Err(e.into());
        },
    }

    println!("--- TAO Cycle Completed. Exiting. ---");

    Ok(()) // 成功完成一个周期并退出
}